package com.cat.controller;

import com.cat.service.Impl.UploadServiceImpl;
import com.cat.service.inter.UploadService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

/**
 * @author :HYC  email: kobe524348@gmail.com
 * @program : HYC_CatRecruit
 * @name : UploadServlet
 * @description : a servlet to upload file
 * @create : 2019-03-24 20:42
 */
@MultipartConfig(location = "C:/Users/Misterchaos/Desktop/")
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doPost(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        UploadService serv = new UploadServiceImpl();
        String stuId = null;

        if (!"".equals(req.getParameter("studentId")) && req.getParameter("studentId") != null) {
            stuId = req.getParameter("studentId");
        }
        Part part = req.getPart("portrait");
        String filename = getFilename(part);
        if (!"".equalsIgnoreCase(filename)) {
            part.write(filename);
            String photo = "/upload/" + filename;
            serv.upload(stuId, photo);
        }
        req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    private String getFilename(Part part) {
        String head = part.getHeader("Content-Disposition");
        String filename = head.substring(
                head.indexOf("filename=\"") + 10,
                head.lastIndexOf("\""));
        return filename;
    }
}
